<?php

namespace App\Components\Consul;

class ConsulProvider
{
    const REGISTER_PATH = '/v1/agent/service/register';//服务注册
    const HEALTH = '/v1/health/service/';//获取健康服务

    /**
     * 注册服务
     * @param $config
     */
    public function registerServer($config)
    {
        if(env('AUTOLOAD_REGISTER'))
        {
            $url = $this->getUrl($config, self::REGISTER_PATH);
            $result = $this->curl_request($url, 'PUT', json_encode($config['register']));
            output()->writeln("<success>Rpc service Register success by consul tcp=" . $config['address'] . ":" . $config['port'] . "</success>");
        }

    }

    /**
     * 排除不健康的服务，获取健康服务, 负载均衡
     * @param $serverName
     * @return bool|string
     */
    public function getServerList($serverName)
    {
        $config = bean('config')->get('provider.consul');
        $url = $this->getUrl($config, self::HEALTH);
        $queryStr = http_build_query($config['discovery']);
        //echo $url.$serverName.'?'.$queryStr;
        //echo "\r\n===\r\n";
        $result = $this->curl_request($url.$serverName.'?'.$queryStr, 'GET');
        //print_r($result);
        //echo "\r\n==============\r\n";
        $result = $this->filterServerList($result, $serverName);

        return $result;
    }

    public function filterServerList($serverList, $serverName)
    {
        $serverList = json_decode($serverList, true);
        $address=[];
        foreach ($serverList as $k=>$v){
            //判断当前的服务是否是活跃的,并且是当前想要去查询服务
            foreach ($v['Checks'] as $c){
                if($c['ServiceName']==$serverName && $c['Status']=="passing"){
                    $address[$k]['address']=$v['Service']['Address'].":".$v['Service']['Port'];
                    $address[$k]['weight']=$v['Service']['Weights']['Passing'];
                }
            }
        }
        return $address;
    }


    public function getUrl($config, $path)
    {
        return 'http://' . $config['address'] . ':' . $config['port'] . $path;
    }


    public function curl_request($url, $method = 'POST', $data = [])
    {
        $method = strtoupper($method);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

}
